package com.ship.system.controller;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.utils.FileUtils;
import com.ship.system.domain.SysDeptMenu;
import com.ship.system.domain.SysMenu;
import com.ship.system.domain.SysUserDept;
import com.ship.system.domain.dto.SysUserUpdateDto;
import com.ship.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ship.common.core.domain.R;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.utils.poi.ExcelUtil;
import com.ship.common.core.web.controller.BaseController;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.core.web.page.TableDataInfo;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.annotation.InnerAuth;
import com.ship.common.security.annotation.RequiresPermissions;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.system.api.domain.SysDept;
import com.ship.system.api.domain.SysRole;
import com.ship.system.api.domain.SysUser;
import com.ship.system.api.model.LoginUser;

/**
 * 用户信息
 * 
 * @author zhangyh
 */
@RestController
@RequestMapping("/user")
@Api(value = "sysUser", tags = "用户信息")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysUserDeptService userDeptService;

    @Autowired
    private ISysDeptMenuService deptMenuService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    /**
     * 获取用户列表
     */
    @ApiOperation(value = "获取用户列表")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @ApiOperation(value = "用户导出")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @ApiOperation(value = "导入用户")
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public JsonResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        FileUtils.checkFileName(file);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return JsonResult.success(message);
    }

    @ApiOperation(value = "导入用户模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @ApiOperation(value = "获取当前用户信息")
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username)
    {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户不存在");
        }
        // 岗位集合
        List<SysUserDept> deptList = userDeptService.getBaseMapper().selectList(
                new LambdaQueryWrapper<SysUserDept>()
                        .eq(SysUserDept::getUserId,sysUser.getUserId())
        );
        List<Long> depts = new LinkedList<>();
        if(deptList.size() > 0){
            depts = deptList.stream().map(SysUserDept::getDeptId).collect(Collectors.toList());
            depts = depts.stream().distinct().collect(Collectors.toList());
        }

        // 权限集合
        List<String> permissions = new LinkedList<>();
        // 管理员拥有所有权限
        if (sysUser.isAdmin()){
            permissions.add("*:*:*");
        }else {
            //先查询是否有个人权限，如果有个人权限则以个人权限为主
            List<String> userMenu = menuService.selectPerms(sysUser.getUserId());
            if(userMenu.size() > 0){
                permissions = userMenu;
            }else{
                if(depts.size() > 0){
                    // 多角色设置permissions属性，以便数据权限匹配权限
                    for (Long deptId : depts)
                    {
                        Set<String> rolePerms = menuService.selectMenuPermsByDeptId(deptId);
                        permissions.addAll(rolePerms);
                    }
                }
            }
        }
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setDepts(depts);
        sysUserVo.setPermissions(permissions);

        if(sysUser.getRefreshStatus() != null && StringUtils.equals(sysUser.getRefreshStatus(),"0")){
            sysUser.setRefreshStatus("1");
            userService.updateUserStatus(sysUser);
        }

        return R.ok(sysUserVo);
    }

    /**
     * 注册用户信息
     */
    @ApiOperation(value = "注册用户信息")
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser)
    {
        String username = sysUser.getUserName();
        if (!userService.checkUserNameUnique(sysUser))
        {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("getInfo")
    public JsonResult getInfo()
    {
        SysUser user = userService.selectUserById(SecurityUtils.getLoginUser().getUserid());
        if(user == null){
            return JsonResult.failed("用户信息异常！");
        }
        // 岗位集合
        List<SysUserDept> deptList = userDeptService.getBaseMapper().selectList(
                new LambdaQueryWrapper<SysUserDept>()
                .eq(SysUserDept::getUserId,user.getUserId())
        );
        List<Long> depts = new LinkedList<>();
        if(deptList.size() > 0){
            depts = deptList.stream().map(SysUserDept::getDeptId).collect(Collectors.toList());
            depts = depts.stream().distinct().collect(Collectors.toList());
        }

        // 权限集合
        List<String> permissions = new LinkedList<>();

        // 管理员拥有所有权限
        if (user.isAdmin()){
            permissions.add("*:*:*");
        }else {
            //先查询是否有个人权限，如果有个人权限则以个人权限为主
            List<String> userMenu = menuService.selectPerms(user.getUserId());
            if(userMenu.size() > 0){
                permissions = userMenu;
            }else{
                if(depts.size() > 0){
                    // 多角色设置permissions属性，以便数据权限匹配权限
                    for (Long deptId : depts)
                    {
                        Set<String> rolePerms = menuService.selectMenuPermsByDeptId(deptId);
                        permissions.addAll(rolePerms);
                    }
                }
            }
        }

        JSONObject ajax = new JSONObject();
        ajax.put("user", user);
        ajax.put("depts", depts);
        ajax.put("permissions", permissions);
        return JsonResult.success(ajax);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation(value = "根据用户编号获取详细信息")
    @GetMapping(value = { "/{userId}" })
    public JsonResult getInfo(@PathVariable(value = "userId") Long userId)
    {
        SysUser user = userService.getUserDeatil(userId);
        String url = user.getSign();
        if (url != null){
            String CsoldPart = "http://10.75.34.224:9300/statics";
            String ZsoldPart = "http://10.75.33.149:9300/statics";
            String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
            String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

            String newUrl = "";
            if (url.contains("http://10.75.34.224:9300/statics")) {
                newUrl = url.replace(CsoldPart, CsPart);
            }else if (url.contains("http://10.75.33.149:9300/statics")){
                newUrl = url.replace(ZsoldPart, ZsPart);
            }else {
                newUrl = url;
            }
            user.setSign(newUrl);
        }
        if(user == null){
            return JsonResult.failed("用户信息异常");
        }
        // 岗位集合
        List<SysDept> deptList = deptService.selectPostListByUserId(userId);
        List<String> posts = new LinkedList<>();
        for (SysDept sysDept : deptList) {
            String ances = sysDept.getAncestors();
            if(ances.indexOf("0,") > -1){
                ances = (ances.substring(2)+","+sysDept.getDeptId());
                posts.add(ances);
            }
        }

        List<String> depts = new LinkedList<>();
        if(user.getDeptId() != null){
            SysDept sysDept = deptService.selectDeptById(user.getDeptId());
            if(sysDept != null){
                String ances = sysDept.getAncestors();
                if(ances.indexOf("0,") > -1){
                    ances = (ances.substring(2)+","+sysDept.getDeptId());
                    depts.add(ances);
                }
            }
        }
        // 权限集合
        List<Long> permissions = new LinkedList<>();
        // 管理员拥有所有权限
        if (!user.isAdmin()){
            //先查询是否有个人权限，如果有个人权限则以个人权限为主
            List<Long> userMenu = menuService.selectMenuIds(user.getUserId());
            if(userMenu.size() > 0){
                permissions = userMenu;
            }else{
                if(deptList.size() > 0){
                    // 多角色设置permissions属性，以便数据权限匹配权限
                    for (SysDept dept : deptList)
                    {
                        Set<Long> rolePerms = menuService.selectMenuIdsByDeptId(dept.getDeptId());
                        permissions.addAll(rolePerms);
                    }
                }
            }
        }else{
            //超管返回所有权限
            Set<Long> rolePerms = menuService.selectMenuIdsByDeptId(null);
            permissions.addAll(rolePerms);
        }
        deptService.resetUserPostInfo(user);

        JSONObject ajax = new JSONObject();
        ajax.put("user", user);
        ajax.put("depts", depts);
        ajax.put("posts", posts);
        ajax.put("menuList", permissions);
        return JsonResult.success(ajax);
    }

    /**
     * 新增用户
     */
    @ApiOperation(value = "新增用户")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public JsonResult add(@Validated @RequestBody SysUser user)
    {
        if (!userService.checkUserNameUnique(user))
        {
            return JsonResult.failed("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return JsonResult.failed("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return JsonResult.failed("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setCreateBy(SecurityUtils.getUsername());
        user.setCreateTime(new Date());
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        return JsonResult.success(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation(value = "修改用户")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public JsonResult edit(@Validated @RequestBody SysUserUpdateDto user)
    {
        return userService.updateUserInfo(user);
    }

    /**
     * 删除用户
     */
    @ApiOperation(value = "删除用户")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public JsonResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId()))
        {
            return JsonResult.failed("当前用户不能删除");
        }
        return JsonResult.success(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @ApiOperation(value = "重置密码")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public JsonResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return JsonResult.success(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @ApiOperation(value = "状态修改")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public JsonResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return JsonResult.success(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @ApiOperation(value = "根据用户编号获取授权角色")
    @GetMapping("/authRole/{userId}")
    public JsonResult authRole(@PathVariable("userId") Long userId)
    {
        JSONObject ajax = new JSONObject();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return JsonResult.success(ajax);
    }

    /**
     * 用户授权角色
     */
    @ApiOperation(value = "用户授权角色")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public JsonResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return JsonResult.success();
    }
}
